<template>
    <div class="fileImport" ref="fileImport" v-loading="fileLoading">
        <el-dialog v-model="importVisible" :title="'导入'" width="576px" @close="closeImport">
            <div class="flex-center" style="align-items: center;">
                <div style="padding-bottom:10px"
                    class="margin-l-r-15px gary-border text-center padding-20px fileImportItem">
                    <span>{{ props.importItem.downTitle || '1、模板下载' }}</span>
                    <img :src="excelImport" alt="">
                    <el-button type="primary" @click="fileDown">{{ props.importItem.downButtonText || '下 载' }}</el-button>
                </div>
                <div class="margin-l-r-15px gary-border text-center padding-20px fileImportItem">
                    <span>{{ props.importItem.upTitle || '2、表格上传' }}</span>
                    <img :src="word" alt="">
                    <el-upload v-model:file-list="fileList" ref="uploadRef" accept=".xls,.xlsx" class="upload-demo"
                        :action="uploadFileUrl" :data="props.importItem.data||{}" multiple :show-file-list="false" :headers="headers"
                        :on-preview="handlePreview" :on-remove="handleRemove" :on-success="onSuccess" :on-error="onError"
                        :before-upload="beforeUpload" :before-remove="beforeRemove" :limit="props.importItem.limit||1" :on-exceed="handleExceed">
                        <el-button>{{ props.importItem.downButtonText || '上 传' }}</el-button>
                        <template #tip>
                            <div class="el-upload__tip">
                                <!-- jpg/png files with a size less than 500KB. -->
                            </div>
                        </template>
                    </el-upload>
                </div>
            </div>
        </el-dialog>
        <el-dialog v-model="resultVisible" @close="closeResult">
            <template #header>
              <span :style="resultData.isSuccess?'color: #12b549' : 'color: #f56c6c'" style="font-size: 20px">{{resultData.title}}</span>
            </template>
            <div class="consequence">
                <div class="consequence-item flex" v-if="resultData.isSuccess">
                    <SuccessFilled style="width:16px;height:16px;color:#12b549" />
                    <span class="margin-l-10px">{{ resultData.successAmount || 0}}条记录导入成功</span>
                </div>
                <div class="consequence-item flex  margin-t-b-20px" v-if="!resultData.isSuccess">
                    <CircleCloseFilled style="width:16px;height:16px;color:#f56c6c" />
                    <span class="margin-l-10px">{{ resultData.errorAmount || 0 }}条数据有误，导致所有数据导入失败，具体原因如下:</span>
                </div>
            </div>
            <div v-if="!resultData.isSuccess">
                <el-table :data="resultData.errorList"
                    :header-cell-style="{ 'text-align': 'center', 'background': '#fff', 'height': '44px' }"
                    :cell-style="{ 'text-align': 'center', 'height': '44px' }" style="max-height:440px;overflow-y: scroll">
                    <el-table-column label="行号" prop="orderNum">
                    </el-table-column>
                    <el-table-column label="失败原因" prop="message"></el-table-column>
                </el-table>
            </div>
            <template #footer>
                <span class="dialog-footer " style="display: block;transform: translateY(20px); ">
                    <el-button type="primary" @click="closeResult">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {ref, onMounted, nextTick, watch, reactive} from 'vue'
import excelImport from '@/assets/images/excelImport2.png'
import word from '@/assets/images/word2.png'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getToken } from "@/utils/auth";
import { download } from "@/utils/request";
const { proxy } = getCurrentInstance();
const uploadFileUrl = ref(import.meta.env.VITE_APP_BASE_API + "/common/upload"); // 上传文件服务器地址
const headers = ref({ Authorization: "Bearer " + getToken() });
const props = defineProps({
    importVisible: { default: false },
    importItem: {
        default: function () {
            return {
                downUrl: '',
                upUrl: '',
                fileDown() { },
                downTitle: '',
                downButtonText: '',
                upButtonText: '',
                upTitle: '',
                blob: false,
            }
        }
    },
})
const emit = defineEmits(['update:importVisible', 'onSuccess', 'onError', 'fileDown', 'successResult'])
const resultData = reactive({
  isSuccess: false,
  title: '',
  successAmount: 0,
  errorAmount: 0,
  errorList: []
})
const fileLoading = ref(false)
const importVisible = ref(false)
const resultVisible = ref(false)
const fileList = ref([])
watch(() => props.importVisible, () => {
    importVisible.value = props.importVisible
})
onMounted(() => {
    if (props.importItem.upUrl) {
        uploadFileUrl.value = import.meta.env.VITE_APP_BASE_API + props.importItem.upUrl
    }
})
const closeImport = () => { clearFileList(); emit("update:importVisible", false) }
const fileDown = () => {
    if (props.importItem.blob) {
        download(props.importItem.downUrl, props.importItem.data, props.importItem.downName || '学员导入模板', {}, {})
        return
    }
    props.importItem.downUrl ? location.href = props.importItem.downUrl : props.importItem.fileDown() || emit('fileDown')
}
// 上传前
const beforeUpload = () => { ElMessage.success('文件上传中，请耐心等待'); fileLoading.value = true}
const onSuccess = (res, uploadFiles) => {
  resultVisible.value = true
  let data = res.rows || res.data || []
  if(res.code === 200) {
    resultData.successAmount = data.totalAmount
    resultData.isSuccess = true
    resultData.title = '导入成功'
    ElMessage.success('文件导入成功')
    fileLoading.value = false
    emit('onSuccess')
  } else if(res.code === 490) {
    resultData.errorAmount = data.errorAmount
    resultData.errorList = data.errorList
    resultData.isSuccess = false
    resultData.title = '导入失败'
    ElMessage.error('文件导入失败')
    fileLoading.value = false
  }
}
const onError = (uploadFile, uploadFiles) => {
    console.log(uploadFile,'uploadFile')
    emit('onError', uploadFile)
    setTimeout(() => {
        ElMessage.warning(uploadFile.msg || '文件上传失败')
        fileLoading.value = false
    }, 300)
}
const handleRemove = (file, uploadFiles) => {
    console.log(file, uploadFiles)
}
const handlePreview = (uploadFile) => {
    console.log(uploadFile)
}
const handleExceed = (files, uploadFiles) => {
    ElMessage.warning(
        `导入限制1个文件`
    )
    // ElMessage.warning(
    //     `The limit is 3, you selected ${files.length} files this time, add up to ${files.length + uploadFiles.length
    //     } totally`
    // )
}
const beforeRemove = (uploadFile, uploadFiles) => {
    return ElMessageBox.confirm(
        `确定移出${uploadFile.name} ?`
    ).then(
        () => true,
        () => false
    )
}

const clearFileList = () => {
    fileList.value = [];
    proxy.$refs["uploadRef"].clearFiles()
};

const initResultData = () => {
  resultData.isSuccess = false
  resultData.title = ''
  resultData.successAmount = 0
  resultData.errorAmount = 0
  resultData.errorList = []
}

function closeResult() {
    initResultData()
    clearFileList()
    resultVisible.value = false
    importVisible.value = false
}


</script>

<style lang="scss" scoped>
:deep(.el-dialog:not(.is-fullscreen)) {
    width: 556px;
    padding-bottom: 30px;
}

.fileImportItem {
    width: 233px;
    height: 211px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    align-items: center;

    span {
        color: rgb(153, 153, 153);
    }

    img {
        margin: 25px;
        width: 60px;
        height: 70px;
    }
}

:deep(.el-dialog__header) {
    text-align: center;

    span {
        font-size: 18px;
    }
}

.consequence {
    .consequence-item {}
}
</style>
